import json

from django.contrib.auth.models import User

from accounts.models import UserProfile
from iyinyue import settings
import time, os


def params_of_request(request):
    content_type = request.META.get('CONTENT_TYPE', '')
    if content_type.startswith('application/json'):
        return json.loads(request.body)

    if request.method == 'POST':
        return request.POST
    else:
        return request.GET


def upload_file_data(f):
    if not f: return None
    filename = time.strftime('%Y%m%d%H%M%S') + str(f)
    fullpath = os.path.join(settings.MEDIA_ROOT, 'photos', filename)
    with open(fullpath, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
    destination.close()
    return (destination, filename)


def create_user(user, posts, files):
    first_name = posts.get('first_name', '')
    last_name = posts.get('last_name', '')
    icon = upload_file_data(files.get('icon', None))
    age = posts.get('age', '')
    phone = posts.get('phone', '')
    desc = posts.get('desc', '')

    userprofile = None
    if not user:
        username = posts.get('username', None)
        if not username:
            return None
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            user = User.objects.create(username=username, password=username)

    try:
        userprofile = user.userprofile
    except Exception as e:
        userprofile = UserProfile.objects.create(user=user)

    if age:
        userprofile.age = age
    if phone:
        userprofile.phone = phone
    if desc:
        userprofile.desc = desc
    if icon:
        import os
        fileurl = os.path.join(userprofile.icon.field.upload_to, icon[1])
        userprofile.icon.name = fileurl

    userprofile.save()

    user.first_name = first_name
    user.last_name = last_name
    user.save()
    return user
